package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.common.ServletUtils;
import com.example.chcrm.entity.consignor.CustomerInfo;
import com.example.chcrm.entity.consignor.CustomerType;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.employee.EssEmployee;
import com.example.chcrm.mapper.CustomerInfoMapper;
import com.example.chcrm.mapper.CustomerTypeMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.service.CustomerInfoService;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/4/20 2:05
 * @Version 1.0
 */
@Service
public class CustomerInfoServiceImpl <T> implements CustomerInfoService <T>{
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private OperateRecordMapper operateRecordMapper;
    @Autowired
    private CustomerTypeMapper customerTypeMapper;
    @Override
    public ResponseMsg<IPage<CustomerInfo>> pageList(CustomerInfo customerInfo, EmployeeVo empVo) {
        QueryWrapper<CustomerInfo> query = new QueryWrapper<>();
        if(StringUtils.isNotBlank(customerInfo.getCustomerName())){
            query.like("customer_name",customerInfo.getCustomerName());
            query.like("customer_simple",customerInfo.getCustomerName());
        }
        if(StringUtils.isNotBlank(customerInfo.getTypeId())){
            query.eq("type_id",customerInfo.getTypeId());
        }
        if(customerInfo.getStatus() != null){
            query.eq("status",customerInfo.getStatus());
        }
        query.eq("is_deleted",0);
        query.orderByDesc("create_time");
        List<CustomerInfo> list = customerInfoMapper.selectList(query);
        ResponseMsg<IPage<CustomerInfo>> iPageResponseMsg = new ResponseMsg<>();
        Page<CustomerInfo> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(customerInfo.getRows());
        page.setCurrent(customerInfo.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> disable(CustomerInfo essEmployee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(essEmployee.getId())){
            msg.fail("未找到选中委托商");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<CustomerInfo>();
        String  res ="";
        if (essEmployee.getStatus()==1){
            updateWrapper.set("status",1);
            updateWrapper.eq("id",essEmployee.getId());
            customerInfoMapper.update(null,updateWrapper);
            res ="启动合作成功";
        }else if(essEmployee.getStatus()==2){
            updateWrapper.set("status",2);
            updateWrapper.eq("id",essEmployee.getId());
            customerInfoMapper.update(null,updateWrapper);
            res ="退出合作成功";
        }else if(essEmployee.getStatus()==0){
//            updateWrapper.set("status",2);
//            updateWrapper.eq("id",essEmployee.getId());
//            customerInfoMapper.update(null,updateWrapper);
            msg.fail("需要审核");
            return msg;
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
             msg.fail("本次操作失败");
            return msg;
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType("修改状态");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        msg.success(res);
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        CustomerInfo customerInfo = customerInfoMapper.selectById(id);
        if (customerInfo != null) {
            // 查询操作记录
            List<OperateRecord> operateRecords = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", customerInfo.getId())
                    .orderByDesc("create_time"));
            customerInfo.setOperateRecordList(operateRecords);
        }
        msg.setData(customerInfo);
        msg.success("查询成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(CustomerInfo customerInfo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(customerInfo.getId())) {
            msg.fail("未找到要修改的委托商");
            return msg;
        }
        
        // 更新数据
        int result = customerInfoMapper.updateById(customerInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_UPDATE);
            operateRecord.setSourceId(customerInfo.getId());
            operateRecord.setRemark("修改委托商信息");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));
            
            // 获取当前登录用户信息
            HttpServletRequest request = ServletUtils.getRequest();
            EmployeeVo empVo = request != null ? (EmployeeVo) request.getAttribute("empVo") : null;
            if (empVo != null) {
                operateRecord.setOperationId(empVo.getId());
                operateRecord.setOperationName(empVo.getEmpNm());
            }
            
            operateRecordMapper.insert(operateRecord);
            msg.success("修改成功");
        } else {
            msg.fail("修改失败");
        }
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> add(CustomerInfo customerInfo, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        
        // 参数校验
        if (StringUtils.isBlank(customerInfo.getCustomerName())) {
            msg.fail("委托商名称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerInfo.getCustomerSimple())) {
            msg.fail("委托商简称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerInfo.getTypeId())) {
            msg.fail("请选择委托商类型");
            return msg;
        }
        CustomerType customerType = customerTypeMapper.selectById(customerInfo.getTypeId());
        customerInfo.setTypeName(customerType.getTypeName());
        if (StringUtils.isBlank(customerInfo.getTelephone())) {
            msg.fail("联系电话不能为空");
            return msg;
        }

        // 检查委托商名称是否已存在
        Long count = customerInfoMapper.selectCount(new QueryWrapper<CustomerInfo>()
                .eq("customer_name", customerInfo.getCustomerName())
                .eq("is_deleted", 0));
        if (count > 0) {
            msg.fail("委托商名称已存在");
            return msg;
        }

        // 设置默认值
        customerInfo.setId(RandomHelper.uuid());
        customerInfo.setIsDeleted(0);
        customerInfo.setCreateTime(new Date());
        customerInfo.setUpdateTime(new Date());
        customerInfo.setStatus(0); // 默认状态为待审核

        // 保存委托商信息
        int result = customerInfoMapper.insert(customerInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_ADD);
            operateRecord.setSourceId(customerInfo.getId());
            operateRecord.setRemark("新增委托商");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));
            
            if (empVo != null) {
                operateRecord.setOperationId(empVo.getId());
                operateRecord.setOperationName(empVo.getEmpNm());
            }
            
            operateRecordMapper.insert(operateRecord);
            msg.success("新增成功");
        } else {
            msg.fail("新增失败");
        }
        return msg;
    }

    @Override
    public ModelAndView export(CustomerInfo customerInfo, EmployeeVo empVo) {
        List<Map<String, Object>> exportList = customerInfoMapper.exportList(customerInfo);
        
        // 转换状态值
        for (Map<String, Object> item : exportList) {
            String status = item.get("status").toString();
            switch (status) {
                case "0":
                    item.put("status", "待审核");
                    break;
                case "1":
                    item.put("status", "合作中");
                    break;
                case "2":
                    item.put("status", "已退出");
                    break;
                default:
                    item.put("status", "未知");
            }
        }
        
        // 设置导出参数
        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());
        modelAndView.addObject(NormalExcelConstants.FILE_NAME, "委托商信息列表");
        modelAndView.addObject(NormalExcelConstants.CLASS, CustomerInfo.class);
        
        if (empVo != null && empVo.getEmpNm() != null) {
            modelAndView.addObject(NormalExcelConstants.PARAMS, 
                new ExportParams("委托商信息列表", "导出人:" + empVo.getEmpNm(), "导出信息"));
        } else {
            modelAndView.addObject(NormalExcelConstants.PARAMS, 
                new ExportParams("委托商信息列表", "导出人:无登录导出", "导出信息"));
        }
        
        modelAndView.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return modelAndView;
    }
}
